<template>
  <div>
    <van-row>
      <van-col style="text-align: right" span="7"
        ><van-icon @click="subtraction" class="prev" name="arrow-left"
      /></van-col>
      <van-col span="10" class="date" @click="show = true"
        ><van-icon name="notes-o" />{{ formatDate(defaultDate) }}</van-col
      >
      <van-col span="7"
        ><van-icon class="next" @click="addition" name="arrow"
      /></van-col>
    </van-row>
    <van-popup v-model="show" position="bottom">
      <van-datetime-picker
        @confirm="ok"
        @cancel="show = false"
        v-model="defaultDate"
        type="year-month"
        title="选择年月"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
      />
    </van-popup>
  </div>
</template>

<script>
export default {
  name: 'datePicker',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: [String],
      default: undefined
    }
  },
  data() {
    return {
      show: false,
      defaultDate: new Date(),
      minDate: new Date(2014, 0, 1),
      maxDate: new Date(new Date().getFullYear() + 1, 11, 1)
    }
  },
  created() {
    let date = new Date()
    this.defaultDate = date
    this.changeEvt(this.formatDate(this.defaultDate))
  },
  watch: {
    defaultDate(val) {
      // this.changeEvt(this.formatDate(val))
    }
  },
  methods: {
    changeEvt(value) {
      this.$emit('change', value)
    },
    formatDate(date) {
      return `${date.getFullYear()}-${
        date.getMonth() + 1 >= 10
          ? date.getMonth() + 1
          : '0' + (date.getMonth() + 1)
      }`
    },
    onConfirm(date) {
      this.show = false
      this.defaultDate = date
    },
    addition() {
      this.defaultDate = new Date(
        this.defaultDate.getFullYear(),
        this.defaultDate.getMonth() + 1
      )
      this.changeEvt(this.formatDate(this.defaultDate))
    },
    subtraction() {
      this.defaultDate = new Date(
        this.defaultDate.getFullYear(),
        this.defaultDate.getMonth() - 1
      )
      this.changeEvt(this.formatDate(this.defaultDate))
    },
    formatter(type, val) {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      }
      return val
    },
    ok() {
      this.changeEvt(this.formatDate(this.defaultDate))
      this.show = false
    }
  }
}
</script>

<style lang='scss' scoped>
.next,
.prev {
  height: 44px;
  background: #ffffff;
  font-size: 14px;
  text-align: center;
  line-height: 44px;
  color: $mainColor;
  width: 54px;
}
.next {
  border-bottom-right-radius: 50%;
  border-top-right-radius: 50%;
}
.prev {
  border-bottom-left-radius: 50%;
  border-top-left-radius: 50%;
}
.date {
  background: $mainColor;
  height: 44px;
  line-height: 44px;
  font-size: 16px;
  color: #ffffff;
  text-align: center;
  i {
    margin-right: 10px;
    font-size: 18px;
  }
}
</style>